import { createRouter, createWebHistory } from "vue-router";
import { useAppStore } from "@/stores";

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_BASE_URL),
  routes: [
    {
      path: "/",
      name: "index",
      meta: { title: "宴会智能排座管理系统" },
      component: () => import("../views/index/index.vue"),
    },
    {
      path: "/sch",
      name: "sch",
      meta: { title: "会议日程" },
      component: () => import("../views/schedule/index.vue"),
    },
    {
      path: "/note",
      name: "note",
      meta: { title: "会议事宜" },
      component: () => import("../views/note/index.vue"),
    },
    {
      path: "/seat",
      name: "seat",
      meta: { title: "座位指引" },
      component: () => import("../views/seat/index.vue"),
    },
    {
      path: "/live",
      name: "live",
      meta: { title: "图文直播" },
      component: () => import("../views/live/index.vue"),
    },
  ],
});

router.beforeEach((to, from, next) => {
  console.log("to", to.query.okey, "from", from.query.okey);
  // 如果目标路由没有 okey，但来源路由有，自动传递
  if (!to.query.okey && from.query.okey) {
    next({
      path: to.path,
      query: {
        ...to.query,
        okey: from.query.okey,
      },
    });
    return;
  }
  setTitle(to.meta.title as string);
  next();
});

function setTitle(t: string) {
  document.title = t;
  // 兼容 WebView 不刷新 title 的 bug
  const ua = navigator.userAgent.toLowerCase();
  if (/micromessenger|qq/i.test(ua)) {
    const iframe = document.createElement("iframe");
    iframe.style.display = "none";
    iframe.src = "/favicon.ico"; // 任意小资源
    document.body.appendChild(iframe);
    iframe.onload = () => {
      setTimeout(() => document.body.removeChild(iframe), 0);
    };
  }
}

export default router;
